package webDemo;

import java.io.IOException;
import java.io.PrintWriter;  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
// 使用 @WebServlet 注解来指定此 Servlet 的 URL 模式
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;  
  
    // 覆盖 HttpServlet 类中的 doGet 方法  
    @Override  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        // 设置响应的内容类型为 HTML  
        response.setContentType("text/html");  
  
        // 获取用于向客户端发送响应的 PrintWriter 对象  
        PrintWriter out = response.getWriter();  
  
        try {  
            // 使用 PrintWriter 对象输出 HTML 内容  
            out.println("<html>");  
            out.println("<head><title>Hello World Servlet</title></head>");  
            out.println("<body>");  
            out.println("<h1>Hello, World!</h1>");  
            out.println("</body>");  
            out.println("</html>");  
        } finally {  
            // 确保 PrintWriter 对象被关闭，以释放资源  
            out.close();  
        }  
    }  
}